﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AzureGames.Data;
using AzureGames.Domain.Contracts;
using AzureGames.Domain.Models;

namespace AzureGames.Domain.Handlers
{
    public class GetGameBoard
    {
        private readonly IBoardRepository _repository;
        private readonly IGameDefinitionRepository _gameDefinitionRepository;
        private readonly IPlayerRepository _playerRepository;

        public GetGameBoard(IBoardRepository gameBoardRepository, IGameDefinitionRepository gameDefinitionRepository, IPlayerRepository playerRepository)
        {
            _repository = gameBoardRepository;
            _gameDefinitionRepository = gameDefinitionRepository;
            _playerRepository = playerRepository;
        }

        public virtual GameBoard Execute(Guid boardID)
        {
            try
            {
                Model.Board board = _repository.GetGameBoard(boardID);
                Model.GameDefinition gameDefinition = _gameDefinitionRepository.GetGameDefinition(board.GameDefinitionID);
                List<GamePlayer> players = new List<GamePlayer>();

                foreach (var playerID in board.PlayerIDs)
                {
                    Model.Player player = _playerRepository.GetPlayer(playerID);
                    players.Add(new GamePlayer(player));

                    if (player is Model.AIPlayer)
                        gameDefinition.JavascriptFiles.Add(((Model.AIPlayer)player).ResourceID);                    
                }

                return new GameBoard(gameDefinition, board, players);
            }
            catch (InvalidOperationException e)
            {
                throw new BusinessServicesException("Unable to retrieve game board from database.", e);
            }
        }
    }
}
